package com.xjrsoft.module.iot.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.enums.IotProtocolEnum;
import com.xjrsoft.common.exception.MyException;
import com.xjrsoft.common.model.result.R;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.common.utils.IotUtil;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.iot.dto.AddIotLinkDto;
import com.xjrsoft.module.iot.dto.IotLinkPageDto;
import com.xjrsoft.module.iot.dto.UpdateIotLinkDto;
import com.xjrsoft.module.iot.entity.IotLink;
import com.xjrsoft.module.iot.service.IIotLinkService;
import com.xjrsoft.module.iot.vo.IotLinkInfoVo;
import com.xjrsoft.module.iot.vo.IotLinkPageVo;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tzx
 * @since 2024-04-10
 */
@RestController
@RequestMapping(GlobalConstant.IOT_MODULE_PREFIX + "/link")
@AllArgsConstructor
public class IotLinkController {

    private final IIotLinkService iotLinkService;

    @GetMapping("/list")
    @ApiOperation(value = "获取数据（不分页）")
    public R list() {

        List<IotLink> list = iotLinkService.list(Wrappers.lambdaQuery(IotLink.class)
                .select(IotLink.class, x -> VoToColumnUtil.fieldsToColumns(IotLink.class).contains(x.getProperty())));
        return R.ok(list);
    }


    @GetMapping(value = "/page")
    @ApiOperation(value="查询物联网连接 (分页)")
    public R page(@Valid IotLinkPageDto dto){

        LambdaQueryWrapper<IotLink> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .like(StrUtil.isNotBlank(dto.getKeyword()),IotLink::getName,dto.getKeyword())
                .orderByDesc(IotLink::getId)
                .select(IotLink.class,x -> VoToColumnUtil.fieldsToColumns(IotLinkPageVo.class).contains(x.getProperty()));


        IPage<IotLink> page = iotLinkService.page(ConventPage.getPage(dto), queryWrapper);
        PageOutput<IotLinkPageVo> pageOutput = ConventPage.getPageOutput(page, IotLinkPageVo.class);

        for (IotLinkPageVo iotLinkPageVo : pageOutput.getList()) {
            if (iotLinkPageVo.getProtocolType() == IotProtocolEnum.MQTT.getCode()) {
                if (IotUtil.cacheMqttClientMap.containsKey(iotLinkPageVo.getId())) {
                    iotLinkPageVo.setStatus(IotUtil.cacheMqttClientMap.get(iotLinkPageVo.getId()).isConnected());
                }
                else {
                    iotLinkPageVo.setStatus(Boolean.FALSE);
                }
            }
            else {
                if (IotUtil.cacheOpcUaClientMap.containsKey(iotLinkPageVo.getId())) {
                    iotLinkPageVo.setStatus(Boolean.TRUE);
                }
                else {
                    iotLinkPageVo.setStatus(Boolean.FALSE);
                }

            }
        }

        return R.ok(pageOutput);
    }

    @GetMapping(value = "/info")
    @ApiOperation(value="根据id 查询 互联网连接详情")
    public R info(@RequestParam Long id){
        IotLink link = iotLinkService.getById(id);
        if (link == null) {
            return R.error("找不到此数据！");
        }
        return R.ok(BeanUtil.toBean(link, IotLinkInfoVo.class));
    }


    @PostMapping
    @ApiOperation(value = "新增互联网连接")
    public R add(@Valid @RequestBody AddIotLinkDto dto){

        return R.ok(iotLinkService.addIotLink(dto));

    }

    @PutMapping
    @ApiOperation(value = "修改互联网连接")
    public R update(@Valid @RequestBody UpdateIotLinkDto dto){

        return R.ok(iotLinkService.updateIotLink(dto));

    }

    @DeleteMapping
    @ApiOperation(value = "删除")
    public R delete(@Valid @RequestBody List<Long> ids){

        List<IotLink> list = iotLinkService.lambdaQuery().in(IotLink::getId, ids).list();

        for (IotLink link : list) {
            if (link.getProtocolType() == IotProtocolEnum.MQTT.getCode()) {
                MqttClient mqttClient = IotUtil.cacheMqttClientMap.get(link.getId());
                try {
                    mqttClient.disconnect();
                } catch (MqttException e) {
                    throw new MyException("移除链接出现问题！");
                }
                IotUtil.cacheMqttClientMap.remove(link.getId());
            }
            else {
                OpcUaClient opcUaClient = IotUtil.cacheOpcUaClientMap.get(link.getId());

                try {
                    opcUaClient.disconnect().get();
                } catch (Exception e) {
                    throw new MyException("移除链接出现问题！");
                }

                IotUtil.cacheOpcUaClientMap.remove(link.getId());
            }
        }

        return R.ok(iotLinkService.removeBatchByIds(ids));

    }

    @PostMapping("/test")
    @ApiOperation(value = "测试链接")
    public R test(@Valid @RequestBody AddIotLinkDto dto){
        return R.ok(iotLinkService.testConnect(dto));
    }
}
